<template>
  <div class="sys-user">

    <AppMainHeader>
      <el-row>
        <el-col :span="22">
          <SysUserQueryForm @query="handleQuery"/>
        </el-col>
        <el-col :span="2" class="align-right">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['sys:user:add']">
            新增
          </el-button>
        </el-col>
      </el-row>
    </AppMainHeader>

    <AppMainContent>
      <SysUserTable
        v-loading="loading"
        :data="userList"
        @row-detail="handleDetail"
        @row-update="handleUpdate"
        @row-reset-pwd="handleResetPwd"
        @row-delete="handleDelete"
      />

<!--      <el-table v-loading="loading" :data="userList">-->
<!--        <el-table-column-->
<!--          label="序号"-->
<!--          align="center"-->
<!--          width="60"-->
<!--          prop="rowNumber"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="姓名"-->
<!--          align="center"-->
<!--          prop="userName"-->
<!--          min-width="10%"-->
<!--          :show-overflow-tooltip="true"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="电话"-->
<!--          align="center"-->
<!--          prop="mobile"-->
<!--          min-width="10%"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="单位"-->
<!--          align="left"-->
<!--          prop="sysCompany.name"-->
<!--          min-width="15%"-->
<!--          :show-overflow-tooltip="true"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="部门"-->
<!--          align="left"-->
<!--          prop="sysDept.name"-->
<!--          min-width="8%"-->
<!--          :show-overflow-tooltip="true"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="类别"-->
<!--          align="center"-->
<!--          prop="category"-->
<!--          min-width="10%"-->
<!--          :formatter="categoryFormat"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="角色"-->
<!--          align="center"-->
<!--          prop="sysRole.name"-->
<!--          min-width="18%"-->
<!--          :show-overflow-tooltip="true"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="是否禁用"-->
<!--          align="center"-->
<!--          prop="isDisabled"-->
<!--          min-width="10%"-->
<!--          :formatter="isDisabledFormat"-->
<!--        />-->
<!--        <el-table-column-->
<!--          label="操作"-->
<!--          align="center"-->
<!--          min-width="15%"-->
<!--          class-name="small-padding fixed-width"-->
<!--        >-->
<!--          <template slot-scope="scope">-->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleDetail(scope.row)"-->
<!--              v-hasPermi="['system:user:detail']"-->
<!--            >-->
<!--              详情-->
<!--            </el-button>-->
<!--            <el-button-->
<!--              v-if="scope.row.id !== '1'"-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleUpdate(scope.row)"-->
<!--              v-hasPermi="['system:user:edit']"-->
<!--            >-->
<!--              修改-->
<!--            </el-button>-->
<!--            <el-button-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleResetPwd(scope.row)"-->
<!--              v-hasPermi="['system:user:resetPwd']"-->
<!--            >-->
<!--              重置密码-->
<!--            </el-button>-->
<!--            <el-button-->
<!--              v-if="scope.row.id !== '1'"-->
<!--              size="mini"-->
<!--              type="text"-->
<!--              @click="handleDelete(scope.row)"-->
<!--              v-hasPermi="['system:user:remove']"-->
<!--            >-->
<!--              删除-->
<!--            </el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->

      <Pagination
        v-show="total > 0"
        :total="total"
        :current.sync="queryParams.pageNum"
        :size.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </AppMainContent>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="530px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="85px"
        :disabled="detailFlag"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>

        <el-form-item label="电话" prop="mobile">
          <el-input
            v-model="form.mobile"
            type="number"
            placeholder="请输入电话"
            @keydown.native="channelInputLimit"
          />
        </el-form-item>

        <el-form-item label="性别">
          <el-select v-model="form.sex" placeholder="请选择" filterable>
            <el-option
              v-for="dict in sexOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="类别" prop="category">
          <el-select
            v-model="form.category"
            placeholder="请选择"
            filterable
            @change="categoryChange"
          >
            <el-option
              v-for="dict in categoryOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="单位" prop="companyId">
          <el-select
            v-model="form.companyId"
            @change="companyChange"
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in companyOptions"
              :key="item.companyID"
              :label="item.companyName"
              :value="item.companyID"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="部门" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择"
            :disabled="deptStatus"
            filterable
          >
            <el-option
              v-for="item in deptOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否禁用">
          <el-select v-model="form.isDisabled" placeholder="请选择" filterable>
            <el-option
              v-for="item in isDisabledOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
              :disabled="item.isDisabled === 1"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="角色" prop="roleId">
          <el-select v-model="form.roleId" placeholder="请选择" filterable>
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.isDisabled === 1"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!detailFlag">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd } from '@/api/system/user'

import SysUserQueryForm from '@/views/system/components/sys-user-query-form'
import SysUserTable from '@/views/system/components/sys-user-table'

import { getCompanyByCategory } from '@/api/system/company'
import { selectDeptList } from '@/api/system/dept'
import { getConfigKey } from '@/api/system/config'

// 新增/更新 用户时，用户所在单位id在以下数组中时，必须选择部门
export default {
  name: 'User',
  components: { SysUserQueryForm, SysUserTable },
  data() {
    return {
      // 必须选择部门的单位id
      configCompanyId: '',
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      isDisabledOptions: [],
      // 用户类别数据字典
      categoryOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 单位选项
      companyOptions: [],
      // 部门选项
      deptOptions: [],
      // 部门是否必选
      deptStatus: true,
      showDept: false,
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        currPage: 1,
        pageSize: 10,
        name: undefined,
        type: undefined
        // orderColumn: undefined,
        // orderDirection: undefined,
      },
      detailFlag: false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        companyId: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        mobile: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        category: [
          { required: true, message: '请选择类别', trigger: 'change' }
        ]
      }
    }
  },
  watch: {},
  created() {
    // this.getList()

    // selectDeptList().then((response) => {
    //   this.deptOptions = response.data
    // })

    // this.getDicts('sys_normal_disable').then((response) => {
    //   this.isDisabledOptions = response.data
    // })
    // this.getDicts('sys_user_category').then((response) => {
    //   this.categoryOptions = response.data
    // })
    // this.getDicts('sys_user_sex').then((response) => {
    //   this.sexOptions = response.data
    // })
    // getConfigKey({id: 'sys.ccqszglzx.company.id'}).then(response => {
    //   this.configCompanyId = response.data;
    // })
  },
  methods: {
    channelInputLimit(e) {
      let key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e' || key === '.') {
        e.returnValue = false
        return false
      }
      return true
    },
    /** 用户类型格式化 **/
    categoryFormat(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category)
    },
    /** 用户状态格式化 **/
    isDisabledFormat(row, column) {
      return this.selectDictLabel(this.isDisabledOptions, row.isDisabled)
    },
    /** 性别格式化 **/
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex)
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.queryParams).then((response) => {
        this.userList = response.data
        this.total = response.page.total
        this.loading = false
      })
    },
    /** 获取全部单位 */
    getCompanyByCategory(category) {
      const query = { category: category }
      getCompanyByCategory(query).then((response) => {
        this.companyOptions = response.data
      })
    },
    /** 选择单位 **/
    categoryChange(val) {
      this.form.companyId = undefined
      this.form.deptId = ''
      this.deptStatus = true
      this.getCompanyByCategory(val)
    },
    /** 选择单位 **/
    companyChange(val) {
      this.form.deptId = ''
      this.form.deptName = ''
      if (val === this.configCompanyId) {
        this.deptStatus = false
      } else {
        this.deptStatus = true
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        companyId: undefined,
        deptId: '',
        name: undefined,
        category: undefined,
        mobile: undefined,
        sex: undefined,
        isDisabled: 0,
        roleId: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.currPage = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.detailFlag = false
      getUser({}).then((response) => {
        this.roleOptions = response.data.roles
        this.open = true
        this.title = '添加用户'
      })
    },
    /** 详情 **/
    async handleDetail(row) {
      this.reset()
      const userId = row.id

      let userRes = await getUser({ id: userId })

      let user = userRes.data.user
      this.form = {
        id: user.id,
        companyId: user.sysCompany.name,
        deptId: user.deptId,
        name: user.userName,
        category: user.category,
        mobile: user.mobile,
        sex: user.sex,
        isDisabled: user.isDisabled,
        roleId: user.roleId
      }

      this.detailFlag = true
      this.roleOptions = userRes.data.roles
      this.open = true
      this.title = '用户详情'
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset()
      const userId = row.id

      let userRes = await getUser({ id: userId })

      let user = userRes.data.user
      this.form = {
        id: user.id,
        companyId: user.companyId,
        deptId: user.deptId,
        name: user.userName,
        category: user.category,
        mobile: user.mobile,
        sex: user.sex,
        isDisabled: user.isDisabled,
        roleId: user.roleId
      }

      await this.getCompanyByCategory(user.category)
      if (user.companyId === 'f492ad2f-f89e-4b40-9844-378fd561b097') {
        this.deptStatus = false
      } else {
        this.deptStatus = true
      }

      this.detailFlag = false
      this.roleOptions = userRes.data.roles
      this.open = true
      this.title = '修改用户'
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$confirm(
        '是否确认重置用户名为"' + row.userName + '"的密码为初始密码?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return resetUserPwd({ id: row.id })
        })
        .then(() => {
          this.msgSuccess('密码重置成功')
        })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateUser(this.form).then((response) => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addUser(this.form).then((response) => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let id = row.id
      this.$confirm(
        '是否确认删除用户名为"' + row.userName + '"的数据项?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delUser({ id })
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
    }
  }
}
</script>
<style>
.vue-treeselect__control {
  padding-left: 5px;
  padding-right: 5px;
  display: table;
  table-layout: fixed;
  width: 100%;
  height: 32px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background: #fff;
}

input[type='number'] {
  -moz-appearance: textfield;
}

input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}
</style>
